package com.xiaoyu.client.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.goods.GoodsDetailBean;
import com.xiaoyu.client.model.goods.GoodsFormatBean;
import com.xiaoyu.client.model.goods.GoodsFormatBean.FormatParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.mall.OrderComfirmActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.widget.LabelsView;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.commonlib.utils.UIUtils;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;


public class SpecificationDialog extends Dialog implements View.OnClickListener {
    private LabelsView mLabelsView;//规格列表
    private ImageView cancelBtn;//取消按钮
    private ImageView goodsImg;//图片
    private TextView priceTxt;//价格
    private TextView inventoryTxt;//库存
    private TextView selectedTxt;//选择的规格
    private TextView lessBtn;//减
    private TextView plusBtn;//加
    private TextView countTxt;//数量
    private TextView commitBtn;//立即购买

    private Context mContext;
    private boolean iscancelable;//控制点击dialog外部是否dismiss
    private boolean isBackCancelable;//控制物理返回键是否dismiss
    private List<FormatParam> mLableList = new ArrayList<>();
    private String lableId;//选中的规格id
    private int num;//购买的商品数量
    private int invenNum;//库存量
    private GoodsDetailBean.DataBean GoodsModel;
    private int index;

    public SpecificationDialog(@NonNull Context context, boolean isCancelable, boolean isBackCancelable) {
        super(context, R.style.MyDialog);
        this.iscancelable = isCancelable;
        this.isBackCancelable = isBackCancelable;
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_format_of_goods);//这行一定要写在前面
        initView();
        setCancelable(iscancelable);//点击外部不可dismiss
        setCanceledOnTouchOutside(isBackCancelable);
        Window window = this.getWindow();
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);


    }

    private void initView() {
        mLabelsView = findViewById(R.id.dialog_format_list);
        cancelBtn = findViewById(R.id.dialog_format_cancel_btn);
        goodsImg = findViewById(R.id.goods_img);
        priceTxt = findViewById(R.id.goods_price);
        inventoryTxt = findViewById(R.id.goods_inventory);
        selectedTxt = findViewById(R.id.goods_format_selected_txt);
        lessBtn = findViewById(R.id.dialog_format_less_btn);
        plusBtn = findViewById(R.id.dialog_format_plus_btn);
        countTxt = findViewById(R.id.dialog_format_count_txt);
        commitBtn = findViewById(R.id.dialog_format_commit_btn);

        countTxt.setText("1");
        lessBtn.setEnabled(false);
        lessBtn.getBackground().setAlpha(50);

        mLabelsView.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(View label, String labelText, int position) {
                mLabelsView.setSelects(position);
                if (!lableId.equals(mLableList.get(position).getGoodsdetailsid())) {
                    selectedTxt.setText(mLableList.get(position).getGoodsdetailsname());//选择的规格
                    Glide.with(mContext).load(mLableList.get(position).getGoodsdeimg()).into(goodsImg);//展示图
                    priceTxt.setText("¥ " + mLableList.get(position).getGoodsprice1());//价格
                    inventoryTxt.setText("库存" + mLableList.get(position).getGoodsinventory() + "件");//库存
                    lableId = mLableList.get(position).getGoodsdetailsid();
                    index = position;
                    invenNum = Integer.parseInt(mLableList.get(position).getGoodsinventory());
                    if (invenNum == 1) {//如果库存量为1时，加1按钮不可点
                        plusBtn.setEnabled(false);
                        plusBtn.getBackground().setAlpha(50);
                    }
                }
            }
        });

        cancelBtn.setOnClickListener(this);
        commitBtn.setOnClickListener(this);
        plusBtn.setOnClickListener(this);
        lessBtn.setOnClickListener(this);
    }

    public static final String GOODS_BUY_INFO = "to buy goods info";
    public static final String GOODS_BUY_COUNT = "to buy goods count";
    public static final String GOODS_BUY_FORMAT = "to buy goods format info";

    @Override
    public void onClick(View v) {
        if (v == cancelBtn) {//取消
            dismiss();
        } else if (v == commitBtn) {//立即购买
            Intent intent = new Intent(mContext, OrderComfirmActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(GOODS_BUY_INFO, GoodsModel);
            bundle.putString(GOODS_BUY_COUNT, countTxt.getText().toString());
            bundle.putSerializable(GOODS_BUY_FORMAT, mLableList.get(index));
            intent.putExtras(bundle);
            mContext.startActivity(intent);
            dismiss();
        } else if (v == lessBtn) {//减
            lessCount();
        } else if (v == plusBtn) {//加
            plusCount();
        }
    }


    /**
     * 数量加1
     */
    private void plusCount() {
        num = Integer.parseInt(countTxt.getText().toString());
        if (num < invenNum) {//小于库存量
            num = num + 1;
            countTxt.setText(num + "");
            lessBtn.setEnabled(true);
            lessBtn.getBackground().setAlpha(255);

            if (num == invenNum) {
                plusBtn.setEnabled(false);
                plusBtn.getBackground().setAlpha(50);
            }

        }

    }

    /**
     * 数量减1
     */
    private void lessCount() {
        num = Integer.parseInt(countTxt.getText().toString());
        if (num > 1) {
            num -= 1;
            countTxt.setText(num + "");
            plusBtn.setEnabled(true);
            plusBtn.getBackground().setAlpha(255);
            if (num == 1) {
                lessBtn.setEnabled(false);
                lessBtn.getBackground().setAlpha(50);
            }
        }
    }


    public void initData(GoodsDetailBean.DataBean goodsMoel) {
        this.GoodsModel = goodsMoel;
        String goodsId = goodsMoel.getGoodsid();
        NetworkManager.getGoodsFormatInfo(goodsId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    private void parseInfoSuc(String result) {
        GoodsFormatBean bean = new Gson().fromJson(result, GoodsFormatBean.class);
        mLableList.clear();
        mLableList.addAll(bean.getData());
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < mLableList.size(); i++) {
            list.add(mLableList.get(i).getGoodsdetailsname());
        }
        mLabelsView.setLabels(list);
        if (mLableList.size() != 0) {
            FormatParam param = mLableList.get(0);
            Glide.with(mContext).load(param.getGoodsdeimg()).into(goodsImg);//展示图
            priceTxt.setText("¥ " + param.getGoodsprice1());//价格
            inventoryTxt.setText("库存" + param.getGoodsinventory() + "件");//库存
            selectedTxt.setText(param.getGoodsdetailsname());//选择的规格
            mLabelsView.setSelects(0);
            index = 0;
            lableId = param.getGoodsdetailsid();

            Log.i("jx", "parseInfoSuc: 库存量===" + param.getGoodsinventory());
//            invenNum = Integer.parseInt(param.getGoodsinventory());
//            if (invenNum == 1) {
//                plusBtn.setEnabled(false);
//                plusBtn.getBackground().setAlpha(50);
//            }
        }
    }


}
